using System.Text;
using LDNS.Interfaces;
using LDNS.SDK.Commands.Models;

namespace LDNS.Commands
{
    /// <summary>
    /// 状态命令处理器
    /// 处理STATUS命令，获取DNS服务状态
    /// 作者：huobing
    /// </summary>
    public class StatusCommandHandler : CommandHandlerBase<StatusCommand, StatusResult>
    {
        private readonly IDnsService _dnsService;
        
        /// <summary>
        /// 命令名称
        /// </summary>
        public override string CommandName => StatusCommand.NAME;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="dnsService">DNS服务实例</param>
        public StatusCommandHandler(IDnsService dnsService)
        {
            _dnsService = dnsService;
        }
        
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args">命令参数</param>
        /// <returns>执行结果</returns>
        public override BaseCommandResult Execute(string[] args)
        {
            try
            {
                var result = CreateSuccessResult("操作成功");
                result.IsRunning = _dnsService.IsRunning;
                if (_dnsService.IsRunning)
                {
                    result.Port = _dnsService.Port;
                }
                
                // 获取并设置版本信息
                result.Version = GetAssemblyVersion();
                
                return result;
            }
            catch (System.Exception ex)
            {
                return CreateErrorResult($"获取服务状态失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取程序集版本信息
        /// </summary>
        /// <returns>程序集版本号</returns>
        private string GetAssemblyVersion()
        {
            try
            {
                // 尝试多种方式获取版本信息
                // 1. 直接从执行目录获取主程序集文件
                string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                string? mainExePath = null;
                
                // 获取主程序集路径
                if (exePath.Contains("LDNS.Commands"))
                {
                    // 如果在Commands项目中，尝试找到主程序集
                    string? baseDir = System.IO.Path.GetDirectoryName(exePath);
                    if (baseDir != null)
                    {
                        mainExePath = System.IO.Path.Combine(baseDir, "LDNS.exe");
                        if (!System.IO.File.Exists(mainExePath))
                        {
                            mainExePath = null;
                        }
                    }
                }
                
                // 如果找到主程序集，尝试获取其版本信息
                if (!string.IsNullOrEmpty(mainExePath))
                {
                    try
                    {
                        var mainAssembly = System.Reflection.Assembly.LoadFile(mainExePath);
                        
                        // 尝试获取InformationalVersion
                        var informationalVersionAttribute = mainAssembly.GetCustomAttributes(typeof(System.Reflection.AssemblyInformationalVersionAttribute), false)
                            .OfType<System.Reflection.AssemblyInformationalVersionAttribute>()
                            .FirstOrDefault();
                        
                        if (informationalVersionAttribute != null && !string.IsNullOrEmpty(informationalVersionAttribute.InformationalVersion))
                        {
                            return informationalVersionAttribute.InformationalVersion;
                        }
                    }
                    catch
                    {
                        // 忽略加载主程序集时的错误
                    }
                }
                
                // 2. 尝试获取入口程序集信息
                var entryAssembly = System.Reflection.Assembly.GetEntryAssembly();
                if (entryAssembly != null)
                {
                    // 尝试获取InformationalVersion
                    var informationalVersionAttribute = entryAssembly.GetCustomAttributes(typeof(System.Reflection.AssemblyInformationalVersionAttribute), false)
                        .OfType<System.Reflection.AssemblyInformationalVersionAttribute>()
                        .FirstOrDefault();
                    
                    if (informationalVersionAttribute != null && !string.IsNullOrEmpty(informationalVersionAttribute.InformationalVersion))
                    {
                        return informationalVersionAttribute.InformationalVersion;
                    }
                    
                    // 尝试获取AssemblyVersion
                    var assemblyVersion = entryAssembly.GetName().Version;
                    if (assemblyVersion != null)
                    {
                        return assemblyVersion.ToString();
                    }
                }
                
                // 3. 尝试获取调用堆栈中的程序集
                var stackTrace = new System.Diagnostics.StackTrace();
                for (int i = 0; i < stackTrace.FrameCount; i++)
                {
                    var frame = stackTrace.GetFrame(i);
                    if (frame != null)
                    {
                        var method = frame.GetMethod();
                        if (method != null && method.DeclaringType != null)
                        {
                            var assembly = method.DeclaringType.Assembly;
                            var informationalVersionAttribute = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyInformationalVersionAttribute), false)
                                .OfType<System.Reflection.AssemblyInformationalVersionAttribute>()
                                .FirstOrDefault();
                            
                            if (informationalVersionAttribute != null && !string.IsNullOrEmpty(informationalVersionAttribute.InformationalVersion))
                            {
                                return informationalVersionAttribute.InformationalVersion;
                            }
                        }
                    }
                }
                
                // 4. 作为最后的尝试，直接返回csproj中配置的版本号
                return "1.0.18";
            }
            catch (Exception ex)
            {
                // 记录异常但不影响状态显示
                System.Diagnostics.Debug.WriteLine($"获取版本信息失败: {ex.Message}");
            }
            
            // 默认返回值
            return "1.0.18";
        }
    }
}